#!/usr/bin/php
<?php

	// read from stdin
	$fd = fopen("php://stdin", "r");
	$email = "";
	while (!feof($fd)) {
		$email .= fread($fd, 1024);
	}
	fclose($fd);


	set_include_path(get_include_path() . PATH_SEPARATOR . './classes/');
	include_once('../config.php');

	$service = new Amazon_SQS_Client(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);

	require_once('classes/mimeparser/rfc822_addresses.php');
	require_once('classes/mimeparser/mime_parser.php');
	$mime = new mime_parser_class;
	
	/*
	 * Set to 0 for parsing a single message file
	 * Set to 1 for parsing multiple messages in a single file in the mbox format
	 */
	$mime->mbox = 0;
	
	/*
	 * Set to 0 for not decoding the message bodies
	 */
	$mime->decode_bodies = 1;

	/*
	 * Set to 0 to make syntax errors make the decoding fail
	 */
	$mime->ignore_syntax_errors = 1;

	/*
	 * Set to 0 to avoid keeping track of the lines of the message data
	 */
	$mime->track_lines = 1;

	$folder = md5(mktime());
//	mkdir("tmp/" . $folder);

	$parameters=array(
#			'File'=> "test.txt"
			'Data' => $email
		/* Save the message body parts to a directory     */
#		,	'SaveBody'=>'tmp/' . $folder . "/"
		,	'SaveBody'=>'tmp/test/'
		/* Do not retrieve or save message body parts     */
		,	'SkipBody'=>1
	);

	$flag = $mime->Decode($parameters, $decoded);
	$email_from = $decoded[0]["ExtractedAddresses"]["from:"][0]["address"];
	$mime->Analyze($decoded[0]["Parts"][0], $results);
print "<br>Stage 1";

#--------------- testing data --------------
/*$basePath = '/home1/silverbi/public_html/clients/gbif/spreadsheet-processor/templates/Merged-Checklist/';
$results["Attachments"] = array(
			  array('Type' => 'ms-excel', 'DataFile' => $basePath . 'checklist-1.1.xlsx')
			, array('Type' => 'ms-excel', 'DataFile' => $basePath . 'checklist-2.1.xlsx')
			);
$email_from = 'balu16@gmail.com';*/
print '<pre>';
#-------------------------------------------

	if (is_array( $results["Attachments"] ) ) {
	foreach( $results["Attachments"] as $attachment ) {
		
		switch( $attachment["Type"] ) {
			case "ms-excel":
print "<br>Stage 2: Found xml file";	
				processFile( stripslashes($attachment["DataFile"]), $email_from );
				break;
		}
	}
	}

#	processFile( "tmp/test/2" );
/*
	function processFile( $uploadfile, $email_from ) {
		// Valid File Do something with it.
		include_once("classes/gbif.general.php");
		include_once("classes/gbif.eml.php");
		$general = new General($uploadfile);
		$sheetType = $general->getSheetType();
		unset($general);
						
		switch( $sheetType ) {				
			case 'Occurrences.0.9.6':
				include_once("classes/gbif.occurrence.php");
				$spreadsheet = new Occurrence( $uploadfile );
				if ( $spreadsheet->validateMetaData() && $spreadsheet->validateOccurrenceData() ) {
		
					$folder = md5(mktime());
					$folder = "test2";
					mkdir("../output/" . $folder);
					
					# Make EML
					$eml = new Eml();
					$worksheet = $spreadsheet->getSheet(1);
					$eml->createEmlFromWorksheet( $worksheet );
					$eml->generateXml(0);
					file_put_contents("../output/" . $folder . "/eml.xml", $eml->getRawXml() );
			
					# Make Meta
					file_put_contents("../output/" . $folder . "/meta.xml", $spreadsheet->generateOccurrenceDataMeta() );
					
					$spreadsheet->writeOccurenceData("../output/" . $folder . "/occurrence.csv");
					$spreadsheet->zipArchive(
							"../output/" . $folder . "/" . $folder . ".zip"
						, "../output/" . $folder . "/"
						, array("eml.xml", "meta.xml", "occurrence.csv")
					);

					require("classes/attach_mailer/attach_mailer_class.php");
				print "Stage 3: Mail File: " . $email_from;	

					$name = "GBIF";
					$from = "nobody@gbif.org";
				#	$to = "mikegiddens@silverbiology.com";
					$to = $email_from;
					$subject = "GBIF - Automated Darwin Core Archive Generator";
					$body = "Body Message";
					$mailer = new attach_mailer($name, $from, $to, $cc, $bcc, $subject, $body);
					$mailer->create_attachment_part("../output/" . $folder . "/" . $folder . ".zip", "attachment", "application/zip"); 
					$mailer->process_mail();
					exit();
				}
				break;

			default:
			case 'Species-Checklist.0.9.8':
				include_once("classes/gbif.species.php");
				$species = new Species( $uploadfile );

				if ( $species->validateMetaData() && $species->validateSpeciesData() && $species->validateVernacularData() ) {
					$folder = md5(mktime());
					$folder = "test";
					@mkdir("output/" . $folder);
					
					# Make EML
					$eml = new Eml();
					$worksheet = $species->getSheet(1);
					$eml->createEmlFromWorksheet( $worksheet );
					$eml->generateXml(0);
					file_put_contents("../output/" . $folder . "/eml.xml", $eml->getRawXml() );
			
					# Make Meta
					file_put_contents("../output/" . $folder . "/meta.xml", $species->generateSpeciesDataMeta() );
					
					$species->writeSpeciesData("../output/" . $folder . "/species.csv");
					$species->writeVernacularData("../output/" . $folder . "/vernacular.csv");
					$species->writeSynonymData("../output/" . $folder . "/synonym.csv");
					$species->writeDistributionData("../output/" . $folder . "/distribution.csv");
					$species->zipArchive(
							"../output/" . $folder . "/" . $folder . ".zip"
						, "../output/" . $folder . "/"
						, array("eml.xml", "meta.xml", "species.csv", "vernacular.csv", "synonym.csv", "distribution.csv")
					);

					require("classes/attach_mailer/attach_mailer_class.php");

					$name = "GBIF";
					$from = "nobody@gbif.org";
				#	$to = "mikegiddens@silverbiology.com";
					$to = $email_from;
					$subject = "GBIF - Automated Darwin Core Archive Generator";
					$body = "Body Message";
					$mailer = new attach_mailer($name, $from, $to, $cc, $bcc, $subject, $body);
					$mailer->create_attachment_part("../output/" . $folder . "/" . $folder . ".zip", "attachment", "application/zip"); 
					$mailer->process_mail();
					exit();

				}
				break;
		}
		
	}
*/


	function processFile( $uploadfile, $email_from ) {
		// Valid File Do something with it.
		global $service, $queueName, $queueUrl;

		# sqs queue populate code
		try {
			# Creating Queue if not present
			$queueRequest = array('QueueName' => $queueName);
			$queueResponse = $service->createQueue($queueRequest);
			if ($queueResponse->isSetCreateQueueResult()) { 
				$createQueueResult = $queueResponse->getCreateQueueResult();
				if ($createQueueResult->isSetQueueUrl()) {
					$queueUrl = $createQueueResult->getQueueUrl();
				}
			}
		# Queue message
			$ar = array();
			$ar['conversionID'] = md5(microtime());
			$ar['status'] = false;
			$ar['path'] = $uploadfile;
			$ar['method'] = 'email'; # whether file upload or email upload
			$ar['email_from'] = $email_from;

echo '<br> Queue Message : ';
print_r($ar);

		# Sending SQS message
			$messageRequest = array('QueueUrl' => $queueUrl, 'MessageBody' => json_encode($ar));
			$response = $service->sendMessage($messageRequest);
			if ($response->isSetSendMessageResult()) {
				$sendMessageResult = $response->getSendMessageResult();
				if ($sendMessageResult->isSetMessageId()) 
				{
		// 			echo '<br> Message Id : ' . $sendMessageResult->getMessageId();
				}
			}
		
		
		} catch (Amazon_SQS_Exception $ex) {
			echo("Caught Exception: " . $ex->getMessage() . "\n<br>");
			echo("Response Status Code: " . $ex->getStatusCode() . "\n<br>");
			echo("Error Code: " . $ex->getErrorCode() . "\n<br>");
			echo("Error Type: " . $ex->getErrorType() . "\n<br>");
			echo("Request ID: " . $ex->getRequestId() . "\n<br>");
			echo("XML: " . $ex->getXML() . "\n<br>");
		}
	}



#					exit();
#	print_r($decoded[0]["Parts"]);
//	mail("mikegiddens@silverbiology.com", "Cool: " . $subject, $message );
?>